package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.UserConstants;
import com.heima.common.exception.CostomException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.feign.ApAuthorFeign;
import com.heima.user.feign.WmUserFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.AppJwtUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author feng js
 */
@Service
@Transactional
public class ApUserRealnameServcieImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto authDto) {
        //检查参数

        if (authDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        authDto.checkParam();
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (authDto.getStatus() != null) {

            lambdaQueryWrapper.eq(ApUserRealname::getStatus, authDto.getStatus());
        }
        //分页
        Page<ApUserRealname> page = new Page<>(authDto.getPage(), authDto.getSize());
        IPage<ApUserRealname> result = page(page, lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(authDto.getPage(), authDto.getSize(), (int) result.getTotal());
        responseResult.setData(result.getRecords());
        return responseResult;
    }

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto authDto, short status) {

        //参数校验
        if (authDto == null || authDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //更新状态
        ApUserRealname userRealname = new ApUserRealname();
        userRealname.setStatus(status);
        userRealname.setId(authDto.getId());
        //失败原因
        if (status == UserConstants.AUTH_FAIL) {
            userRealname.setReason(authDto.getMsg());
        }
        updateById(userRealname);


        //判断是否通过审核，通过审核
        if (status == UserConstants.AUTH_PASS) {
            //创建自媒体账号//创建作者
            ResponseResult result = createWmUserAndAuthor(authDto);
            if (result != null) {
                return result;
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    ApAuthorFeign apAuthorFeign;
    @Autowired
    WmUserFeign wmUserFeign;

    private ResponseResult createWmUserAndAuthor(AuthDto authDto) {
        Integer rid = authDto.getId();
        ApUserRealname apUserRealname = getById(rid);
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        //创建自媒体账号
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = wmUserFeign.findByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            ResponseResult result = wmUserFeign.save(wmUser);
            if (result.getCode() != 0) {
               throw new CostomException(ResponseResult.errorResult(AppHttpCodeEnum.AUTH_FAIL));
            }
        }

        // 创建作者
        creatAuthor(wmUser);

        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    // 创建作者
    private void creatAuthor(WmUser wmUser) {
        Integer apUserId = wmUser.getApUserId();
        ApAuthor apAuthor = apAuthorFeign.findById(apUserId);
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(apUserId);
            apAuthor.setType(2);
            ResponseResult result = apAuthorFeign.save(apAuthor);
            if (result.getCode() != 0) {
                throw new CostomException(ResponseResult.errorResult(AppHttpCodeEnum.AUTH_FAIL));
            }
        }
    }

    @Override
    public ResponseResult longin(LoginDto dto) {
        if (dto.getEquipmentId() == null && StringUtils.isBlank(dto.getPassword()) && StringUtils.isBlank(dto.getPhone())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //使用账号密码登录
        if (StringUtils.isNotBlank(dto.getPassword()) && StringUtils.isNotBlank(dto.getPhone())) {

            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser != null) {

                String md5Password = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                if (apUser.getPassword().equals(md5Password)) {
                    String token = AppJwtUtil.getToken((long) apUser.getId());
                    Map<String, Object> map = new HashMap<>();
                    map.put("token", token);
                    apUser.setSalt("");
                    apUser.setPassword("");
                    map.put("user",apUser);
                    return ResponseResult.okResult(map);

                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }

            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }

        } else {
            //设备登录
            if (dto.getEquipmentId() == null) {

                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);

        }

    }
}
